package com.gitee.mall.user.controller;

import com.gitee.common.utils.R;
import com.gitee.mall.user.feign.OrderFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    public R findOrderByUserId(@PathVariable("id") Integer id) {
        log.info("根据userId:" + id + "查询订单信息");

        //String url = getUri("mall-order") + "/order/findOrderByUserId/" + id;
        //R result = restTemplate.getForObject(url, R.class);
        R result = orderFeignService.findOrderByUserId(id);
        return result;
    }

    @Autowired
    private DiscoveryClient discoveryClient;
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private String getUri(String serviceId) {

        List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
        int index = chooseInstance(instanceList.size());
        return instanceList.get(index).getUri().toString();
    }

    public int chooseInstance(int module) {
        for (; ; ) {
            int current = atomicInteger.get();
            int next = (current + 1) % module;
            if (atomicInteger.compareAndSet(current, next) && current < module) {
                return current;
            }
        }
    }

}
